#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: other_ui.py
# Author: ChenChangSong
# Date: 2025-08-24

"""
功能描述: 其他 页面 UI。
"""

from PyQt5.QtWidgets import (
    QGridLayout,
    QPushButton,
    QVBoxLayout,
    QWidget,
    QLineEdit,
    QDateEdit,
    QHBoxLayout,
    QSizePolicy,
    QLabel,
)
from PyQt5.QtCore import Qt, QDate
import datetime
import sys
import os
import openpyxl
from .common_ui import LogPanel, get_project_root
from function_code.other.release_requirements_or_bug_infor import release_requirements_or_bug_info
from function_code.other.testing_meeting import testing_meeting
from function_code.other.performance_info import get_performance_info
from function_code.other.other_functions_3 import other_function_3
from function_code.other.other_functions_4 import other_function_4
from function_code.other.other_functions_5 import other_function_5
from function_code.other.other_functions_6 import other_function_6
from function_code.other.other_functions_7 import other_function_7
from function_code.other.other_functions_8 import other_function_8
from function_code.other.other_functions_9 import other_function_9
from function_code.other.other_functions_10 import other_function_10
from function_code.other.other_functions_11 import other_function_11

class OtherPage(QWidget):
    def __init__(self) -> None:
        super().__init__()
        self._init_ui()

    def _init_ui(self) -> None:
        root = QVBoxLayout(self)
        root.setSpacing(10)

        # 添加查询区域
        search_layout = QHBoxLayout()
        search_layout.setSpacing(15)
        search_layout.setAlignment(Qt.AlignLeft)  # 设置布局内容左对齐
        
        # 查询姓名标签和输入框
        name_label = QLabel("查询姓名：")
        search_layout.addWidget(name_label)
        self.name_input = QLineEdit()
        self.name_input.setPlaceholderText("请输入要查询的人名")
        self.name_input.setMaxLength(10)
        self.name_input.setMinimumWidth(300)  # 设置合理的输入框宽度
        self.name_input.setMaximumWidth(200)
        search_layout.addWidget(self.name_input)
        
        # 设置默认值为Excel中第二行第五列的值，如果为空则使用空字符串
        try:
            # 获取Excel文件路径
            excel_path = get_project_root() / "files" / "config_file" / "confg.xlsx"
            if excel_path.exists():
                workbook = openpyxl.load_workbook(str(excel_path))
                ws = workbook.active  # 使用活动工作表
                # 获取第二行第五列的值，如果不存在则使用空字符串
                default_name = ws.cell(row=2, column=5).value or ""
                self.name_input.setText(default_name)
        except Exception as e:
            # 如果读取Excel失败，不影响界面启动，只在日志中记录
            pass
        
        # 计算本周的开始（周一）和结束（周日）日期
        today = datetime.datetime.now()
        # 获取本周一（0表示周一，6表示周日）
        days_since_monday = today.weekday()
        monday = today - datetime.timedelta(days=days_since_monday)
        # 获取本周日
        sunday = monday + datetime.timedelta(days=6)
        
        # 时间标签和开始日期组件
        time_label = QLabel("          时间(输入或选择)：")
        search_layout.addWidget(time_label)
        self.start_date_edit = QDateEdit()
        self.start_date_edit.setCalendarPopup(True)
        self.start_date_edit.setDisplayFormat("yyyy-MM-dd")
        # 设置默认值为本周一
        self.start_date_edit.setDate(QDate(monday.year, monday.month, monday.day))
        self.start_date_edit.setMinimumWidth(150)  # 设置合理的日期组件宽度
        self.start_date_edit.setMaximumWidth(180)
        search_layout.addWidget(self.start_date_edit)
        
        # 分隔符标签
        separator_label = QLabel("→")
        search_layout.addWidget(separator_label)
        
        # 结束日期组件
        self.end_date_edit = QDateEdit()
        self.end_date_edit.setCalendarPopup(True)
        self.end_date_edit.setDisplayFormat("yyyy-MM-dd")
        # 设置默认值为本周日
        self.end_date_edit.setDate(QDate(sunday.year, sunday.month, sunday.day))
        self.end_date_edit.setMinimumWidth(150)  # 设置合理的日期组件宽度
        self.end_date_edit.setMaximumWidth(180)
        self.end_date_edit.setAlignment(Qt.AlignLeft)  # 设置组件内文本左对齐
        search_layout.addWidget(self.end_date_edit)
        
        # 添加伸展空间在末尾，确保所有组件靠左
        search_layout.addStretch(1)
        
        root.addLayout(search_layout)
        
        # 添加说明文本
        root.addWidget(QLabel("说明！上方输入的任意姓名、时间，默认全局生效（除了“今日发布需求/BUG信息(发车司机)”功能）。"))

        grid = QGridLayout()
        grid.setHorizontalSpacing(15)
        grid.setVerticalSpacing(12)
        
        # 按钮样式设置函数
        def set_button_style(button, min_width=150):
            button.setMinimumWidth(min_width)
            button.setMinimumHeight(36)
            button.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        
        # 今日发布需求/BUG信息按钮
        self.btn_release_today = QPushButton("今日发布需求/BUG信息(发车司机)")
        set_button_style(self.btn_release_today, 180)
        grid.addWidget(self.btn_release_today, 0, 0)
        
        # 其他功能按钮
        self.btn_other_1 = QPushButton("测试例会填写")
        self.btn_other_2 = QPushButton("获取填写绩效的信息")
        self.btn_other_3 = QPushButton("其他功能3(待开发)")
        self.btn_other_4 = QPushButton("其他功能4(待开发)")
        self.btn_other_5 = QPushButton("其他功能5(待开发)")
        self.btn_other_6 = QPushButton("其他功能6(待开发)")
        self.btn_other_7 = QPushButton("其他功能7(待开发)")
        self.btn_other_8 = QPushButton("其他功能8(待开发)")
        self.btn_other_9 = QPushButton("其他功能9(待开发)")
        self.btn_other_10 = QPushButton("其他功能10(待开发)")
        self.btn_other_11 = QPushButton("其他功能11(待开发)")
        
        # 设置所有按钮样式
        for btn in [
            self.btn_other_1, self.btn_other_2, self.btn_other_3, 
            self.btn_other_4, self.btn_other_5, self.btn_other_6, 
            self.btn_other_7, self.btn_other_8, self.btn_other_9, 
            self.btn_other_10, self.btn_other_11
        ]:
            set_button_style(btn)
        
        # 添加到网格布局，调整布局使其更加紧凑
        grid.addWidget(self.btn_other_1, 0, 1)
        grid.addWidget(self.btn_other_2, 0, 2)
        grid.addWidget(self.btn_other_3, 1, 0)
        grid.addWidget(self.btn_other_4, 1, 1)
        grid.addWidget(self.btn_other_5, 1, 2)
        grid.addWidget(self.btn_other_6, 2, 0)
        grid.addWidget(self.btn_other_7, 2, 1)
        grid.addWidget(self.btn_other_8, 2, 2)
        grid.addWidget(self.btn_other_9, 3, 0)
        grid.addWidget(self.btn_other_10, 3, 1)
        grid.addWidget(self.btn_other_11, 3, 2)

        root.addLayout(grid)

        self.log_panel = LogPanel()
        root.addWidget(self.log_panel)

        # 连接按钮事件
        self.btn_release_today.clicked.connect(self._release_requirements_or_bug_info)
        self.btn_other_1.clicked.connect(self._testing_meeting)
        self.btn_other_2.clicked.connect(self._get_performance_info)
        self.btn_other_3.clicked.connect(self._other_function_3)
        self.btn_other_4.clicked.connect(self._other_function_4)
        self.btn_other_5.clicked.connect(self._other_function_5)
        self.btn_other_6.clicked.connect(self._other_function_6)
        self.btn_other_7.clicked.connect(self._other_function_7)
        self.btn_other_8.clicked.connect(self._other_function_8)
        self.btn_other_9.clicked.connect(self._other_function_9)
        self.btn_other_10.clicked.connect(self._other_function_10)
        self.btn_other_11.clicked.connect(self._other_function_11)

    def _release_requirements_or_bug_info(self):
        # 清空屏幕日志
        self.log_panel.clear_screen_logs()
        try:
            release_requirements_or_bug_info()
        except Exception as e:
            self.log_panel.append_log(f"执行今日发布需求/BUG信息功能时出错: {str(e)}")

    def _testing_meeting(self):
        # 清空屏幕日志
        self.log_panel.clear_screen_logs()
        try:
            # 获取姓名输入
            name_value = self.name_input.text().strip()
            if not name_value:
                self.log_panel.append_log("请输入查询姓名")
                return
            
            # 获取选择的日期并减去7天
            # 开始日期减去7天
            selected_start_date = self.start_date_edit.date()
            previous_start_date = selected_start_date.addDays(-7)
            
            # 结束日期减去7天
            selected_end_date = self.end_date_edit.date()
            previous_end_date = selected_end_date.addDays(-7)
            
            # 格式化日期为字符串
            start_date_str = previous_start_date.toString("yyyy-MM-dd")
            end_date_str = previous_end_date.toString("yyyy-MM-dd")
            
            # 按照testing_meeting函数要求的格式拼接时间字符串
            time_value = f"{start_date_str} 00:00,{end_date_str} 23:59"
            
            # 调用testing_meeting函数并传递参数
            testing_meeting(name_value, time_value)
        except Exception as e:
            self.log_panel.append_log(f"执行时间段内的工作统计时出错: {str(e)}")

    def _get_performance_info(self):
        # 清空屏幕日志
        self.log_panel.clear_screen_logs()
        try:
            # 获取姓名输入
            name_value = self.name_input.text().strip()
            if not name_value:
                self.log_panel.append_log("请输入查询姓名")
                return
            
            # 获取选择的日期
            start_date_str = self.start_date_edit.date().toString("yyyy-MM-dd")
            end_date_str = self.end_date_edit.date().toString("yyyy-MM-dd")
            
            # 按照要求的格式拼接时间字符串
            time_value = f"{start_date_str} 00:00,{end_date_str} 23:59"
            
            # 调用get_performance_info函数并传递参数
            get_performance_info(name_value, time_value)
        except Exception as e:
            self.log_panel.append_log(f"执行获取绩效信息时出错: {str(e)}")

    def _other_function_3(self):
        # 清空屏幕日志
        self.log_panel.clear_screen_logs()
        try:
            other_function_3()
            self.log_panel.append_log("已执行其他功能3")
        except Exception as e:
            self.log_panel.append_log(f"执行其他功能3时出错: {str(e)}")

    def _other_function_4(self):
        # 清空屏幕日志
        self.log_panel.clear_screen_logs()
        try:
            other_function_4()
            self.log_panel.append_log("已执行其他功能4")
        except Exception as e:
            self.log_panel.append_log(f"执行其他功能4时出错: {str(e)}")

    def _other_function_5(self):
        # 清空屏幕日志
        self.log_panel.clear_screen_logs()
        try:
            other_function_5()
            self.log_panel.append_log("已执行其他功能5")
        except Exception as e:
            self.log_panel.append_log(f"执行其他功能5时出错: {str(e)}")

    def _other_function_6(self):
        # 清空屏幕日志
        self.log_panel.clear_screen_logs()
        try:
            other_function_6()
            self.log_panel.append_log("已执行其他功能6")
        except Exception as e:
            self.log_panel.append_log(f"执行其他功能6时出错: {str(e)}")

    def _other_function_7(self):
        # 清空屏幕日志
        self.log_panel.clear_screen_logs()
        try:
            other_function_7()
            self.log_panel.append_log("已执行其他功能7")
        except Exception as e:
            self.log_panel.append_log(f"执行其他功能7时出错: {str(e)}")

    def _other_function_8(self):
        # 清空屏幕日志
        self.log_panel.clear_screen_logs()
        try:
            other_function_8()
            self.log_panel.append_log("已执行其他功能8")
        except Exception as e:
            self.log_panel.append_log(f"执行其他功能8时出错: {str(e)}")

    def _other_function_9(self):
        # 清空屏幕日志
        self.log_panel.clear_screen_logs()
        try:
            other_function_9()
            self.log_panel.append_log("已执行其他功能9")
        except Exception as e:
            self.log_panel.append_log(f"执行其他功能9时出错: {str(e)}")

    def _other_function_10(self):
        # 清空屏幕日志
        self.log_panel.clear_screen_logs()
        try:
            other_function_10()
            self.log_panel.append_log("已执行其他功能10")
        except Exception as e:
            self.log_panel.append_log(f"执行其他功能10时出错: {str(e)}")

    def _other_function_11(self):
        # 清空屏幕日志
        self.log_panel.clear_screen_logs()
        try:
            other_function_11()
            self.log_panel.append_log("已执行其他功能11")
        except Exception as e:
            self.log_panel.append_log(f"执行其他功能11时出错: {str(e)}")